package cn.jcby.app.config;

import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.geotools.geojson.geom.GeometryJSON;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;

import java.io.StringReader;
import java.io.StringWriter;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: lihaotian
 * @since: 2023/12/7 12:34
 * @description
 **/
public class GeometryTypeHandler extends AbstractJsonTypeHandler<Geometry> {
    private static final WKTReader WKT_READER = new WKTReader();
    private static final GeometryJSON geometryJSON =  new GeometryJSON();
    public GeometryTypeHandler() {
        super();
    }
    @Override
    protected Geometry parse(String json) {
        try {
            return WKT_READER.read(json);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected String toJson(Geometry obj) {
        try {
            StringWriter writer = new StringWriter();
            geometryJSON.write(obj,writer) ;
            return geometryJSON.read(new StringReader(writer.toString())).toText();
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, toJson(parameter));
    }

    @Override
    public Geometry getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parse(rs.getString(columnName));
    }

    @Override
    public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parse(rs.getString(columnIndex));
    }

    @Override
    public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parse(cs.getString(columnIndex));
    }
}
